<template>
  <el-dialog v-if="openForm" v-model="openBoole" :close-on-click-modal="false" :title="title" custom-class="mydialog"
    width="50%" @close="close">
    <el-form ref="openRef" :model="openForm" :rules="rules" label-width="110px" size="small">
      <el-row gutter="40">
        <el-col v-if="num === 2" :span="24">
          <el-form-item label="终端编号：">
            {{ terminalNo }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="终端名称" prop="terminalName">
            <el-input v-model="openForm.terminalName" clearable placeholder="请输入终端名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="简称" prop="terminalAlias">
            <el-input v-model="openForm.terminalAlias" clearable placeholder="请输入简称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="终端类型" prop="terminalType">
            <el-select v-model="openForm.terminalType" placeholder="请选择终端类型" style="width: 100%"
              @change="handlTerminalType">
              <el-option v-for="item in terminalData.filter(a=>a.value !== 'all')" :key="item.id" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="label" prop="childProperty">
            <el-select v-model="openForm.childProperty" :placeholder="placeholder" style="width: 100%">
              <el-option v-for="item in classification" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所在地区" prop="value">
            <el-cascader v-model="openForm.value" :options="cityList" :popper-append-to-body="false"
              :props="{ value:'regionCode',label:'regionName', expandTrigger: 'hover' }" placeholder="请选择地区"
              style="width:100%" @change="handlCity" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所在街道" prop="streetCode">
            <el-select v-model="openForm.streetCode" :disabled="openForm.areaCode === ''" placeholder="请选择街道"
              style="width: 100%;">
              <el-option v-for="item in streetList" :key="item.value" :label="item.regionName" :value="item.regionCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属营销区域" prop="saleValue">
            <el-cascader v-model="openForm.saleValue" :options="salesArea" :popper-append-to-body="false"
              :props="{checkStrictly: true, value:'id',label:'salesAreaName' }" placeholder="所属营销区域" style="width:100%"
              @change="handlArea" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="openForm.address" clearable placeholder="请输入详细地址" />
          </el-form-item>
        </el-col>
        <el-col v-show="openForm.terminalType === 'first_terminal'" :span="12">
          <el-form-item label="分级标准" prop="terminalLevel">
            <el-select v-model="openForm.terminalLevel" clearable placeholder="请选择分级标准" style="width: 100%">
              <el-option v-for="item in standard" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-show="openForm.terminalType === 'first_terminal'" :span="12">
          <el-form-item label="年门诊量" prop="cureNum">
            <el-input v-model="openForm.cureNum" clearable placeholder="请输入年门诊量" @change="handlCurNum">
              <template #append>
                <span>万人次</span>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人" prop="contacts">
            <el-input v-model="openForm.contacts" clearable placeholder="请输入联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="tel">
            <el-input v-model="openForm.tel" clearable placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer" style="display:flex;justify-content:center;align-items:center;">
        <el-button class="border-btn" size="small" style="margin-right: 20px;" @click="close">取消</el-button>
        <el-button v-if=" sub.boole" class="border-btn" size="small" style="margin-right: 20px;" @click="handlSave">
          保存并新建
        </el-button>
        <el-button class="main-btn" size="small" type="primary" @click="handlSubmit">{{ sub.title }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  getCurrentInstance,
  inject,
  nextTick,
  onMounted,
  reactive,
  ref,
  toRefs,
  watch,
} from "vue";
import area from "@/utils/area";
import {
  recursive,
  validateVENumber,
  validateVETel,
  marketingArea,
} from "@/utils/validate";
import { crmStore } from "@CRM/store";

export default {
  name: "RuleForm",
  props: {
    typeStr: {
      type: String,
      default() {
        return "create";
      },
    },
    formType: {
      type: String,
      default() {
        return "";
      },
    },
    sub: {
      type: Object,
      default() {
        return {
          boole: true,
          title: "保存",
          msg: "",
        };
      },
    },
    clueId: {
      type: Number,
      default: 0,
    },
  },
  setup(props, context) {
    //* ************自定义效验**********
    const validateTel = (rule, value, callback) => {
      if (value === "") {
        callback();
      } else {
        if (validateVETel(value)) {
          callback(new Error("手机号格式不正确"));
        } else {
          callback();
        }
      }
    };

    const validateNum = (rule, value, callback) => {
      if (value === "" || value === null) {
        callback();
      } else {
        if (validateVENumber(value)) {
          callback(new Error("格式不正确(最多保留两位小数)"));
        } else {
          callback();
        }
      }
    };

    const validateNanem = async (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入终端名称"));
      } else {
        const aaa = await validateVEName(value);
        if (aaa) {
          callback(new Error("终端名称重复"));
        } else {
          callback();
        }
      }
    };
    //* ********************************
    const api = inject("api");
    var data = reactive({
      openBoole: false,
      title: "新建潜在终端",
      label: "医院属性",
      cityList: area,
      openForm: {
        terminalName: "", // 终端名称
        terminalAlias: "", // 终端简称
        terminalType: "first_terminal", // 终端类型key
        childProperty: "", // 子分类
        provinceCode: "", // 省code
        cityCode: "", // 市code
        areaCode: "", // 区code
        address: "", // 详细地址
        contacts: "", // 联系人
        tel: "", // 联系电话
        saleAreaId: null, // 所属营销区域
        saleAreaName: "",
        terminalLevel: "", // 分级标准
        cureNum: null, // 年就诊人
        value: [],
        saleValue: [],
        formType: props.formType,
        streetCode: "",
      },
      placeholder: "请选择医院属性",
      rules: {
        terminalName: [
          { required: true, validator: validateNanem, trigger: "blur" },
        ],
        terminalType: [
          { required: true, message: "请选择终端类型", trigger: "change" },
        ],
        childProperty: [
          { required: true, message: "请选择", trigger: "change" },
        ],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
        saleValue: [
          { required: true, message: "请选择所属营销区域", trigger: "change" },
        ],
        value: [{ required: true, message: "请选择地区", trigger: "change" }],
        // streetCode: [
        //   { required: true, message: "请选择街道", trigger: "change" },
        // ],
        tel: [{ validator: validateTel, trigger: "blur" }],
        cureNum: [{ validator: validateNum, trigger: "blur" }],
      },
      openRef: null,
      terminalData: crmStore.getters["dictionary/getDictionary"]["app_mode"],
      classification:
        crmStore.getters["dictionary/getDictionary"]["first_terminal"],
      standard:
        crmStore.getters["dictionary/getDictionary"]["classification_standard"],
      salesArea: [],
      num: 1,
      terminalNo: "",
      streetList: [],
    });
    const currentInstance = getCurrentInstance();

    const validateVEName = async (val) => {
      let paramData = {
        table: "terminal_info",
        column: "terminal_name",
        column_data: val,
        id: data.openForm.id ? data.openForm.id : "",
      };
      let booleName = false;
      let res = await api.channelAgent.POTENTIALAGENT_NAME(paramData);
      if (res.code === 0) {
        if (res.data.exist === "1") {
          booleName = true;
        } else {
          booleName = false;
        }
      } else {
        booleName = false;
      }
      return booleName;
    };

    const handlTerminalType = (val) => {
      if (val === "first_terminal") {
        data.label = "医院属性";
        data.placeholder = "请选择医院属性";
        data.classification =
          crmStore.getters["dictionary/getDictionary"]["first_terminal"];
      }
      if (val === "second_terminal") {
        data.label = "子分类";
        data.placeholder = "请选择子分类";
        data.openForm.terminalLevel = "";
        data.openForm.cureNum = "";
        data.classification =
          crmStore.getters["dictionary/getDictionary"]["second_terminal"];
      }

      if (val === "third_terminal") {
        data.label = "子分类";
        data.placeholder = "请选择子分类";
        data.openForm.terminalLevel = "";
        data.openForm.cureNum = "";
        data.classification =
          crmStore.getters["dictionary/getDictionary"]["third_terminal"];
      }
      data.openForm.childProperty = "";
    };

    const handlCity = (val) => {
      if (val) {
        data.openForm.saleValue = [];
        data.openForm.provinceCode = val[0];
        data.openForm.cityCode = val[1];
        data.openForm.areaCode = val[2];
        if (data.openForm.areaCode) {
          handleStreet(data.openForm.areaCode);
        }
        nextTick((_) => {
          data.openRef.clearValidate("provinceCode");
        });

        console.log(val[2], data.salesArea);
        console.log(marketingArea(val[2], data.salesArea));
        var a_id = marketingArea(val[2], data.salesArea);
        if (a_id) {
          var region = recursive(
            data.salesArea,
            a_id?.id,
            "id",
            "salesAreaName"
          );
          data.openForm.saleValue = region?.idList;
          data.openForm.saleAreaId = a_id?.id;
          var a = region?.nameList;
          var b = "";
          for (let i = 0; i < a.length; i++) {
            b += a[i];
            if (i === a.length - 1) {
            } else {
              b = b + "/";
            }
          }
          data.openForm.saleAreaName = b;
          console.log(data.openForm.saleAreaName, data.openForm.saleAreaId);
        }
      }
    };

    const handleStreet = (val) => {
      api.common.GET_SYS_REGION_STREET(val).then((res) => {
        if (res.code === 0) {
          data.streetList = res.data || [];
        }
      });
    };

    const handlCurNum = (val) => {
      data.openForm.cureNum = Number(val);
    };

    const handlSalesArea = () => {
      api.terminal.TERMINAL_TREE().then((res) => {
        if (res.code === 0) {
          data.salesArea = res.data;
        }
      });
    };

    const handlArea = (val) => {
      data.openForm.saleAreaId = val[val.length - 1];
      const a = recursive(
        data.salesArea,
        data.openForm.saleAreaId,
        "id",
        "salesAreaName"
      )?.nameList;
      let b = "";
      for (let i = 0; i < a.length; i++) {
        b += a[i];
        if (i === a.length - 1) {
        } else {
          b = b + "/";
        }
      }
      data.openForm.saleAreaName = b;
      console.log(b, "-------");
    };

    const close = () => {
      data.openBoole = false;
      handlRemove();
    };

    const handlRemove = () => {
      data.openForm.cityCode = "";
      data.openForm.areaCode = "";
      data.openForm.address = "";
      data.label = "医院属性";
      data.placeholder = "请选择医院属性";
      data.classification =
        crmStore.getters["dictionary/getDictionary"]["first_terminal"];
      data.openRef.clearValidate();
      data.openRef.resetFields();
    };

    const open = (id, num,obj) => {
      data.openBoole = true;
      data.num = num;
      // handlRemove()
      if (id && num === 2) {
        handlDetail(id);
      }
      if (id && num === 3) {
        handlDetail(id);
      }

      if (obj){
        data.openForm.value = [obj.provinceCode,obj.cityCode,obj.areaCode]
        data.openForm.address = obj.address
        data.openForm.tel = obj.contactPhone
        data.openForm.contacts = obj.contactName
        data.openForm.provinceCode = obj.provinceCode;
        data.openForm.cityCode = obj.cityCode;
        data.openForm.areaCode = obj.areaCode;
        data.openForm.terminalName = obj.company

        if (data.openForm.areaCode) {
          handleStreet(data.openForm.areaCode);
        }
      }
    };

    const handlSave = () => {
      data.openRef.validate((valid) => {
        if (valid) {
          api.terminal.TERMINAL_CREATE(data.openForm).then((res) => {
            if (res.code === 0) {
              currentInstance.proxy.customMessage({
                type: "success",
                message: "创建成功",
              });
              context.emit("succsess");
              handlRemove();
            } else {
              currentInstance.proxy.customMessage({
                type: "error",
                message: res.msg,
              });
            }
          });
        }
      });
    };

    const handlSubmit = () => {
      data.openRef.validate((valid) => {
        if (valid) {
          const commit = ref(undefined);
          const msgs = ref("");
          if (data.num === 2) {
            commit.value = api.terminal.TERMINAL_EDIT;
            msgs.value = "修改成功";
          } else if (data.num === 3) {
            commit.value = api.editorial.EDITORIAL_CUSTOMER_TERMINAL_UPDATE;
            msgs.value = "确认成功";
          } else {
            commit.value = api.terminal.TERMINAL_CREATE;
            if (props.sub.title === "保存") {
              msgs.value = "创建成功";
            }
            if (props.sub.title === "提交审核") {
              msgs.value = "提交成功";
            }
          }
          commit.value(data.openForm, props.clueId).then((res) => {
            if (res.code === 0) {
              currentInstance.proxy.customMessage({
                type: "success",
                message: props.sub.msg ? props.sub.msg : msgs.value,
              });
              context.emit("succsess");
              close();
            } else {
              currentInstance.proxy.customMessage({
                type: "error",
                message: res.msg,
              });
            }
          });
        }
      });
    };

    watch(
      () => props,
      (newVal, oldVal) => {
        if (newVal !== null) {
          if (newVal.typeStr === "create") {
            data.title = "新建潜在终端";
          }
          if (newVal.typeStr === "editor") {
            data.title = "变更终端信息";
          }
          if (newVal.typeStr === "change") {
            data.title = "编辑终端信息";
          }
        }
      },
      { deep: true }
    );

    const handlDetail = (id) => {
      api.terminal.TERMINAL_DETAIL(id).then((res) => {
        if (res.code === 0) {
          if (res.data.terminal.terminalType === "first_terminal") {
            data.label = "医院属性";
            data.placeholder = "请选择医院属性";
            data.classification =
              crmStore.getters["dictionary/getDictionary"]["first_terminal"];
          }
          if (res.data.terminal.terminalType === "second_terminal") {
            data.label = "子分类";
            data.placeholder = "请选择子分类";
            console.log(1111111111111111);
            data.classification =
              crmStore.getters["dictionary/getDictionary"]["second_terminal"];
          }
          if (res.data.terminal.terminalType === "third_terminal") {
            data.label = "子分类";
            data.placeholder = "请选择子分类";
            data.classification =
              crmStore.getters["dictionary/getDictionary"]["third_terminal"];
          }
          for (const key in res.data.terminal) {
            data.openForm[key] = JSON.parse(JSON.stringify(res.data.terminal))[
              key
            ];
          }
          data.terminalNo = res.data.terminal.terminalNo;
          data.openForm.value = [
            data.openForm.provinceCode,
            data.openForm.cityCode,
            data.openForm.areaCode,
          ];
          if (data.openForm.areaCode) {
            handleStreet(data.openForm.areaCode);
          }
          data.openForm.id = Number(id);
          data.openForm.saleValue = recursive(
            data.salesArea,
            data.openForm.saleAreaId,
            "id",
            "salesAreaName"
          )?.idList;
          console.log(
            recursive(
              data.salesArea,
              data.openForm.saleAreaId,
              "id",
              "salesAreaName"
            ),
            data.openForm.saleAreaId
          );
        }
      });
    };

    onMounted(() => {
      handlSalesArea();
    });
    return {
      ...toRefs(data),
      close,
      open,
      handlSubmit,
      handlTerminalType,
      handlCurNum,
      handlCity,
      handlSave,
      handlRemove,
      validateVEName,
      handlArea,
      handleStreet,
    };
  },
};
</script>

<style scoped>
/* @import url(); 引入css类 */
</style>
